const {
  remote,
  contextBridge,
  ipcRenderer,
  clipboard,
  Notification,
} = require('electron')
const { createProtocol } = require('vue-cli-plugin-electron-builder/lib')

// 在渲染进程中使用 contextBridge 来暴露安全的 API
contextBridge.exposeInMainWorld('electronApi', {
  // 操作文件
  fileSend: (message) =>
    ipcRenderer.send('fileSendSocket', JSON.stringify(message)),
  fileOn: (callback) => ipcRenderer.on('fileOnSocket', callback),
  // 复制
  clipboard: (value) => {
    clipboard.writeText(value)
    const notification = new Notification({
      title: '复制成功',
      body: '文本已复制到剪贴板',
    })
    notification.show()
  },
  // 通知
  notification: (options) => new Notification(options),
})

// 右键菜单
const createRightMenu = () => {
  let mainWin = remote.getCurrentWindow()
  const contextTemp = [
    {
      label: '刷新',
      click: () => {
        mainWin.setAlwaysOnTop(!mainWin.isAlwaysOnTop())
        mainWin.reload()
      },
    },
    {
      type: 'checkbox',
      checked: mainWin.isAlwaysOnTop(),
      label: '置顶',
      click: () => {
        mainWin.setAlwaysOnTop(!mainWin.isAlwaysOnTop())
      },
    },
  ]
  const Menu = remote.Menu
  const menu = Menu.buildFromTemplate(contextTemp)

  window.addEventListener(
    'contextmenu',
    (e) => {
      e.preventDefault()
      menu.popup({ window: remote.getCurrentWindow() })
    },
    false
  )
}

// 创建新窗口
const createPreloadWindow = async (filename) => {
  let win = new remote.BrowserWindow({
    width: 800,
    height: 600,
    title: '麻雀',
    show: false,
    frame: false,
    center: true,
    icon: path.resolve(__dirname, './public/favicon.ico'),
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL + filename)
  } else {
    createProtocol('app')
    win.loadURL(`app://./${filename}.html`)
  }

  win.on('close', () => (win = null))
}

// controls按钮绑定相应事件
const controlsBind = () => {
  const divDoms = document.getElementById('controls').children
  if (!divDoms) return false
  let mainWin = remote.getCurrentWindow()
  const events = [
    // 迷你
    () => {
      if (!mainWin.isMinimized()) {
        mainWin.minimize()
      }
    },
    // 最大化，最小化
    () => {
      if (!mainWin.isMaximized()) {
        mainWin.maximize()
      } else {
        // 还原
        mainWin.restore()
      }
    },
    // 关闭当前窗口
    () => mainWin.close(),
  ]
  Array.from(divDoms).forEach((element, index) => {
    element.addEventListener('click', events[index])
  })
}

window.addEventListener('DOMContentLoaded', () => {
  controlsBind()
  createRightMenu()
  // createPreloadWindow('preload');
})
